package com.kt.delivery.controller;

import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralRequest;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralResponse;
import com.aliyun.ocr_api20210707.models.RecognizeGeneralResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.google.gson.Gson;
import com.kt.delivery.domain.R;
import com.kt.delivery.domain.vo.Station;
import com.kt.delivery.utils.MachingUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName AliyunOcrController
 * @Description TODO
 * @Author ghs
 * @Date 2024-04-03 21:44
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/ocr")
public class AliyunOcrController {

    @Resource
    private Client client;

    @Resource
    private MachingUtils machingUtils;

    @PostMapping("/ocrFile")
    public R OcrTest(@RequestParam("file") MultipartFile file) throws IOException {
        RecognizeGeneralRequest request = new RecognizeGeneralRequest();
        request.setBody(file.getInputStream());
        try {
            RecognizeGeneralResponse response = client.recognizeGeneral(request);
            String json = new Gson().toJson(response.getBody());

            RecognizeGeneralResponseBody body = response.getBody();
            String[] split = json.split(",");

            String replace = split[1].split(":")[1].replace("\\", "");

            System.out.println(replace);

            // 匹配驿站信息
            List<Station> stations = machingUtils.extractStationInfo(replace);

//            // 匹配手机尾号
//            List<String> phone = machingUtils.extractPhoneTail(json);
//
//            //匹配快递公司
//            List<String> company = machingUtils.extractExpressCompany(json);
//
//            // 匹配取件码
//            List<String> code = machingUtils.extractPickupCode(json);


//            Map<String,Object> map  = new HashMap<>();
//            map.put("station",stationInfo);
//            map.put("phone",phone);
//            map.put("company",company);
//            map.put("code",code);

            return R.ok(stations);

//            return R.ok(response.getBody());
        } catch (TeaException error) {
            Common.assertAsString(error.message);
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            // 如有需要，请打印 error
            System.out.println(Common.assertAsString(error.message));
        }
        return null;
    }

}
